use std::process::{exit, Command};
use crate::net::veth_peer::VethPeer;

pub fn init_container_net(pid:String,ip_1:String,ip_2:String)->VethPeer {
    //创建veth peer网卡对
    let mut veth_peer = VethPeer::new(pid.clone());
    veth_peer.veth_create_peer_netns0();
    let veth1 = veth_peer.get_veth1();
    //把veth1放入容器
    veth1.set_ns(pid.to_string());
    //设置容器内 veth1 ip
    veth1.ip_with_ns(ip_1.clone());
    //设置容器内 veth1 启动
    veth1.up_with_ns();
    //设置容器内 lo interface 启动
    lo_interface_up_with_ns(pid.to_string());
    let veth0 = veth_peer.get_veth0();
    //设置父命名空间 veth0 ip
    veth0.ip_without_ns(ip_2.clone());
    //设置父命名空间 veth0 启动
    veth0.up_without_ns();
    veth_peer
}

pub fn lo_interface_up_with_ns(pid:String){
    let mut child = Command::new("nsenter")
        .args(["-t", &pid, "-n", "ip", "link", "set", "lo", "up"])
        .spawn().expect("Failed to lo_interface_up_with_ns");
    let status = child.wait().expect("Failed to lo_interface_up_with_ns");
    if !status.success() {
        exit(status.code().unwrap_or(3));
    }
}